package com.dabbo.starship.app.server;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Date;

import com.dabbo.starship.container.Universe;
import com.dabbo.starship.interfaces.PlayerPoolInterface;
import com.dabbo.starship.interfaces.ServerCommand;
import com.dabbo.starship.player.PlayerPool;

public class ServerApp extends java.rmi.server.UnicastRemoteObject {

	private static final long serialVersionUID = 9141818899230715378L;

	// Pointless change (test)
	
	Registry reg1;
	Registry reg2;
	
	PlayerPoolInterface playerPool;
	//Container cp;
	Universe universe;
	ServerCommand sc;
	
	int ticker = 0;

	public ServerApp() throws RemoteException {
		//cp = new ContainerShip("USS Dabbo");
		universe = new Universe();
		sc = new ServerCommandState();
		playerPool = new PlayerPool();
		try {
			sc.setCommand(ServerCommand.CMD_RUNNING);
			reg1 = LocateRegistry.createRegistry(3232);
			reg1.rebind("universe", universe);
			reg1.rebind("pool", playerPool);
			reg2 = LocateRegistry.createRegistry(3233);
			reg2.rebind("cmd", sc);
		} catch (RemoteException ex) {
			throw ex;
		}
	}
	
	public boolean shutdownServerInitiated() throws RemoteException {
		if (this.sc.getCommand().equals(ServerCommand.CMD_SHUTDOWN)) {
			try {
				reg1.unbind("universe");
				reg1.unbind("pool");
				reg2.unbind("cmd");
				log("Command: " + ServerCommand.CMD_SHUTDOWN);
			} catch (Exception ex) {
				log("Critical Error occurred when attempting shutdown.");
			}
			return true;
		}
		return false;
	}
	
	public String displayCommand() throws RemoteException {
		try {
			return this.sc.getCommand();
		} catch (Exception ex) {
			log("Error occurred when attempting to read server command!");
		}
		return "";
	}
	
	private void tick() throws RemoteException {
		universe.tick();
	}
	
	public static void log(String msg) {
		System.out.println(new Date() + " :: " + msg);
	}
	
	
	public static void main(String args[]) throws RemoteException {

		ServerApp server = new ServerApp();
		log("Server running.");
		
		int ticker = 0;
		
		while(!server.shutdownServerInitiated()) {
			ticker++;
			if (ticker > 80) {
				ticker = 0;
				log("State: " + server.displayCommand());
			}
			server.tick();
			try {
				Thread.sleep(800);
			} catch (Exception ex) {
				System.out.println("Thread exception raised!");
				System.exit(1);
			}
		}
	
		log("Server shut-down.");
		System.exit(0);
	}
}
